package com.example.localareanetworkchat.login

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.example.localareanetworkchat.persistence.dao.UserDao
import com.example.localareanetworkchat.persistence.database.ChatDatabase
import com.example.localareanetworkchat.persistence.entity.User
import com.example.localareanetworkchat.persistence.factory.ChatDatabaseFactory
import java.security.MessageDigest
import java.util.*

class LoginViewModel(application: Application) : AndroidViewModel(application) {

    private var chatDatabase: ChatDatabase ?= null
    private var userDao: UserDao ?= null

    init {
        chatDatabase = ChatDatabaseFactory(getApplication()).chatDatabase
        userDao = chatDatabase!!.userDao()
    }

    fun checkDuplicatedUser(name: String): Boolean = userDao?.queryByName(name)!! > 0
    fun checkLogin(name: String, password: String): User? = userDao?.queryByNameAndPassword(name, MessageDigest.getInstance("MD5").digest(password.toByteArray()).decodeToString())
    fun insertUser(name: String, password: String): User? {

        val encodePassword = MessageDigest.getInstance("MD5").digest(password.toByteArray()).decodeToString()
        val uid = System.currentTimeMillis().toString()

        userDao?.insert(User(0, name, encodePassword, uid))
        return checkLogin(name, password)

    }

    fun checkLoginTextContent(str: String): Boolean = str.trim().isEmpty().or(str.trim().isBlank())


}